//
//  ZSPSearchMoreController.m
//  ZSP_IOS
//
//  Created by Bruce on 2019/10/7.
//  Copyright © 2019 mlqk. All rights reserved.
//

#import "ZSPSearchMoreController.h"
//view
#import "ZSP_SearchBar.h"
#import "ZSPSearchLabel.h"
#import "ZSPSearchResultViewCell.h"
#import "ZSPUIBarButtonItem.h"

//model
#import "ZSPSearchResultModel.h"

//
#import "ZSPSearchManager.h"


@interface ZSPSearchMoreController () <UISearchBarDelegate>
@property(nonatomic, strong) ZSP_SearchBar *searchBars;
@property(nonatomic, strong) UIButton *cancelButton;
@property(nonatomic, strong) UIView *searchView;
@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) ZSPSearchLabel *emptyLabel;

@end

@implementation ZSPSearchMoreController

- (instancetype)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        self.isShowSeachBar = YES;
    }
    return self;
}

- (UILabel *)emptyLabel {
    if (!_emptyLabel) {
        self.emptyLabel = [[ZSPSearchLabel alloc] initWithFrame:CGRectMake(10, 45, self.view.frame.size.width - 20, 16)];
        self.emptyLabel.font = [UIFont systemFontOfSize:14.f];
        self.emptyLabel.textAlignment = NSTextAlignmentCenter;
        self.emptyLabel.numberOfLines = 0;
        [self.tableView addSubview:self.emptyLabel];
    }
    return _emptyLabel;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
        _headerView.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 40 - 16 - 7, self.view.frame.size.width, 16)];
        label.font = [UIFont systemFontOfSize:14.];
        label.text = self.type;
        label.textColor = RGBACOLOR(0x999999);
        [_headerView addSubview:label];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 39.5, self.view.frame.size.width - 10, 0.5)];
        view.backgroundColor = RGBACOLOR(0xdfdfdf);
        [self.headerView addSubview:view];
    }
    return _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.isShowSeachBar) {
        [self loadSearchView];
        self.navigationItem.titleView = self.searchView;
        self.searchBars.text = self.searchString;
    }
    NSString *imageStr = nil;
    if (self.isShowSeachBar) {
        imageStr = @"searchBack";
    } else {
        imageStr = @"navigator_btn_back";
    }
//    ZSPUIBarButtonItem *leftButton = [[ZSPUIBarButtonItem alloc] initContainImage:[UIImage imageNamed:imageStr] imageViewFrame:CGRectMake(0, 4, 10, 17) buttonTitle:nil
//                                                                       titleColor:nil
//                                                                       titleFrame:CGRectZero
//                                                                      buttonFrame:CGRectMake(-6, 0, 30, 23)
//                                                                           target:self
//                                                                           action:@selector(leftBarButtonBackAction)];
//    [self.navigationItem setLeftBarButtonItem:leftButton];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorColor = RGBACOLOR(0xdfdfdf);
}

- (void)leftBarButtonBackAction {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadSearchView {
    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    self.searchView.backgroundColor = [UIColor whiteColor];
    
    _searchBars = [[ZSP_SearchBar alloc] initWithFrame:CGRectZero];
    _searchBars.backgroundColor = [UIColor whiteColor];
    _searchBars.delegate = self;
    _searchBars.tintColor = [UIColor blueColor];
    [_searchBars becomeFirstResponder];
    _searchBars.frame = CGRectMake(MY_Padding, (44 - 36)/2.0, self.searchView.frame.size.width - 65, 36);
    [self.searchView addSubview:self.searchBars];
    _searchBars.backgroundColor = MY_VC_Back_Gray_Color;
    _searchBars.layer.masksToBounds = YES;
    _searchBars.layer.cornerRadius = 36/2.0;
    
    _cancelButton = [[UIButton alloc]
                     initWithFrame:CGRectMake(CGRectGetMaxX(_searchBars.frame) - 3, CGRectGetMinY(self.searchBars.frame), 55, 36)];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:RGBACOLOR(0x0099ff) forState:UIControlStateNormal];
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:18.];
    [_cancelButton addTarget:self action:@selector(cancelButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//    [self.searchView addSubview:_cancelButton];
}


- (void)cancelButtonClicked {
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.tableHeaderView = self.headerView;
    [[ZSPSearchManager shareInstance] initData];

    if (self.isShowSeachBar) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor] ;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(MY_TopSafeMargin, 10, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(MY_TopSafeMargin, 10, 0, 0)];
    }
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.resultArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZSPSearchResultViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[ZSPSearchResultViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if (self.searchBars.text) {
        cell.searchString = self.searchBars.text;
    } else {
        cell.searchString = self.searchString;
    }
    [cell setDataModel:self.resultArray[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.searchBars resignFirstResponder];
    ZSPSearchResultModel *model = self.resultArray[indexPath.row];
    if(model.searchType == ZSPSearchLocal)
    {
        //通讯录好友 直接跳转
      
        return;
    }
    else if (model.searchType ==  ZSPSearchZSPGroup)
    {
        NSString *groupId = model.targetId;

       
    }
    else if (model.searchType == ZSPSearchUSer)
    {
        
    }
    else if (model.searchType == ZSPSearchChatHistory)
    {
        //聊天记录
//        NIMSession *session = [NIMSession session:model.targetId type:model.sessionType];
//
//        ZSPSessionVC *vc = [[ZSPSessionVC alloc] initWithSession:session];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        //其他
//        NIMSession *session = [NIMSession session:model.targetId type:model.sessionType];
//
//        ZSPSessionVC *vc = [[ZSPSessionVC alloc] initWithSession:session];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.text = nil;
    searchBar.placeholder = self.type;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.resultArray = nil;
    NSInteger type = 0;
    if ([self.type isEqualToString:ZSPSearchFriendString]) {
        type = ZSPSearchFriend;
    } else if ([self.type isEqualToString:ZSPSearchZSPGroupString]) {
        type = ZSPSearchZSPGroup;
    } else if ([self.type isEqualToString:ZSPSearchGroupString]) {
        type = ZSPSearchGroup;
    }else if ([self.type isEqualToString:ZSPSearchChatHistoryString]) {
        type = ZSPSearchChatHistory;
    }
    else if ([self.type isEqualToString:ZSPSearchLocalString]) {
        type = ZSPSearchLocal;
    }
    else if ([self.type isEqualToString:ZSPSearchUSerString]) {
        type = ZSPSearchUSer;
    }
    __weak typeof(self) weakSelf = self;
    [[ZSPSearchManager shareInstance] searchDataWithSearchText:searchText
                                                      bySearchType:type
                                                          complete:^(NSDictionary *dic, NSArray *array) {
                                                              weakSelf.resultArray = [dic objectForKey:weakSelf.type];
                                                              dispatch_async(dispatch_get_main_queue(), ^{
                                                                  [weakSelf refreshSearchView:searchText];
                                                              });
                                                          }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBars resignFirstResponder];
}

- (void)refreshSearchView:(NSString *)searchText {
    [self.tableView reloadData];
    NSString *searchStr = [searchText stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (!self.resultArray.count && searchText.length > 0 && searchStr.length > 0) {
        NSString *str = [NSString stringWithFormat:@"没有搜索到“%@”相关的内容", searchText];
        self.emptyLabel.textColor = RGBACOLOR(0x999999);
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:RGBACOLOR(0x0099ff)
                                 range:NSMakeRange(6, searchText.length)];
        self.emptyLabel.attributedText = attributedString;
        CGFloat height = [self labelAdaptive:str];
        CGRect rect = self.emptyLabel.frame;
        rect.size.height = height;
        self.emptyLabel.frame = rect;
        self.emptyLabel.hidden = NO;
        self.tableView.tableHeaderView = nil;
    } else {
        self.emptyLabel.hidden = YES;
        if (self.resultArray.count > 0) {
            self.tableView.tableHeaderView = self.headerView;
        } else {
            self.tableView.tableHeaderView = nil;
        }
    }
}

- (CGFloat)labelAdaptive:(NSString *)string {
    float maxWidth = self.view.frame.size.width - 20;
    CGRect textRect =
    [string boundingRectWithSize:CGSizeMake(maxWidth, 8000)
                         options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin |
                                  NSStringDrawingUsesFontLeading)
                      attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14.0]}
                         context:nil];
    textRect.size.height = ceilf(textRect.size.height);
    return textRect.size.height + 5;
}
@end
